"""
@file: Events.py
@author: lingdubing
@time: 2024/10/31  14:09
@desc: FastAPI 应用事件
@character: utf-8
"""

from typing import Callable

from fastapi import FastAPI
from database.mysql import register
from database.redis import code_cache,token_cache,task_cache



def startup(app: FastAPI) -> Callable:
    """
    FastApi 启动完成事件
    :param app: FastAPI
    :return: start_app
    """

    async def app_start() -> None:
        # APP启动完成后触发
        print("-------------fsray-api-alpha start-------------")
        print("晴空一鹤排云上,便引诗情到碧霄")
        print("@author lingdubing")

        # 注册数据库
        await register()
        # 初始化redis
        app.state.task_cache = await task_cache()
        app.state.code_cache = await code_cache()
        app.state.token_cache = await token_cache()
        pass

    return app_start


def stopping(app: FastAPI) -> Callable:
    """
    FastApi 停止事件
    :param app: FastAPI
    :return: stop_app
    """

    async def stop_app() -> None:
        # APP停止时触发
        task: Redis = await app.state.task_cache
        code: Redis = await app.state.code_cache
        token: Redis = await app.state.token_cache
        await task.close()
        await code.close()
        await token.close()
        print("-------------fsray-api-alpha stop-------------")
        print("郴江幸自绕郴山，为谁流下潇湘去")
        print("@author lingdubing")

    return stop_app
